using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using System.Collections.Generic;
using CreditAgricole.Framework;

namespace CreditAgricole.CommonElements.Features.CA_Knowlegdes_List
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("04b8b932-4879-48e5-977e-99067b9446a1")]
    public class CA_Knowledge_List_and_Content_TypeEventReceiver : SPFeatureReceiver
    {
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            CALoggingHelper.AddInformationEntry(string.Format("Feature {0} ({1}) activated.", properties.Feature.Definition.DisplayName, properties.Feature.DefinitionId));

            SPWeb web = properties.Feature.Parent as SPWeb;

            if (web != null)
            {
                bool allowUnsafeUpdates = web.AllowUnsafeUpdates;
                web.AllowUnsafeUpdates = true;

                // Create Approvers Groups Lvl 1 & 2 if not presents
                if (SPHelper.SearchGroup(Constants.KnowledgeApproversLvl1GroupName, web) == null)
                {
                    web.SiteGroups.Add(Constants.KnowledgeApproversLvl1GroupName, web.Author, web.Author, Constants.KnowledgeApproversLvl1GroupDescription);
                    CALoggingHelper.AddInformationEntry(string.Format("Group {0} created.", Constants.KnowledgeApproversLvl1GroupName));
                }
                else
                    CALoggingHelper.AddInformationEntry(string.Format("Group {0} already exists.", Constants.KnowledgeApproversLvl1GroupName));


                if (SPHelper.SearchGroup(Constants.KnowledgeApproversLvl2GroupName, web) == null)
                {
                    web.SiteGroups.Add(Constants.KnowledgeApproversLvl2GroupName, web.Author, web.Author, Constants.KnowledgeApproversLvl2GroupDescription);
                    CALoggingHelper.AddInformationEntry(string.Format("Group {0} created.", Constants.KnowledgeApproversLvl2GroupName));
                }
                else
                    CALoggingHelper.AddInformationEntry(string.Format("Group {0} already exists.", Constants.KnowledgeApproversLvl2GroupName));

                try
                {
                    SPGroup grp = web.SiteGroups[Constants.KnowledgeApproversLvl1GroupName];
                    if (grp.OnlyAllowMembersViewMembership)
                    {
                        grp.OnlyAllowMembersViewMembership = false;
                        grp.Update();
                        CALoggingHelper.AddInformationEntry(string.Format("Visibility of membership set to Everyone for group '{0}'.", Constants.KnowledgeApproversLvl1GroupName));
                    }
                    grp = web.SiteGroups[Constants.KnowledgeApproversLvl2GroupName];
                    if (grp.OnlyAllowMembersViewMembership)
                    {
                        grp.OnlyAllowMembersViewMembership = false;
                        grp.Update();
                        CALoggingHelper.AddInformationEntry(string.Format("Visibility of membership set to Everyone for group '{0}'.", Constants.KnowledgeApproversLvl2GroupName));
                    }
                }
                catch (SPException ex)
                {
                    CALoggingHelper.AddErrorEntry(ex.Message);
                }
                finally
                {
                    web.Update();
                }


                // Ajouter traitements sur liste (champ title, association groupes, ...)
                SPDocumentLibrary doclib = web.Lists[Constants.KnowledgeUnapprovedListTitle] as SPDocumentLibrary;
                if (doclib != null)
                {
                    // Hide title field (replaced by custom title, required)
                    SPHelper.HideField(doclib, "Title");

                    // Change Group filter for ApproverLvl1 field
                    SPGroup grp = SPHelper.SearchGroup(Constants.KnowledgeApproversLvl1GroupName, web);
                    if (grp != null)
                    {
                        SPFieldUser approver = null;

                        try
                        {
                            approver = doclib.Fields.GetFieldByInternalName(Constants.FirstApproverField) as SPFieldUser;
                        }
                        catch { }

                        if (approver != null)
                        {
                            approver.SelectionGroup = grp.ID;
                            approver.SelectionMode = SPFieldUserSelectionMode.PeopleOnly;
                            approver.Update();
                            CALoggingHelper.AddInformationEntry(string.Format("The {0} field has been associated with \"{1}\" group.", approver.InternalName, grp.Name));
                        }
                        else
                        {
                            CALoggingHelper.AddWarningEntry(string.Format("The {0} field cannot be found.", approver.InternalName, doclib.Title));
                        }
                    }

                    // Change Group filter for ApproverLvl2 field
                    grp = SPHelper.SearchGroup(Constants.KnowledgeApproversLvl2GroupName, web);
                    if (grp != null)
                    {
                        SPFieldUser approver = null;

                        try
                        {
                            approver = doclib.Fields.GetFieldByInternalName(Constants.SecondApproverField) as SPFieldUser;
                        }
                        catch { }

                        if (approver != null)
                        {
                            approver.SelectionGroup = grp.ID;
                            approver.SelectionMode = SPFieldUserSelectionMode.PeopleOnly;
                            approver.Update();
                            CALoggingHelper.AddInformationEntry(string.Format("The {0} field has been associated with \"{1}\" group.", approver.InternalName, grp.Name));
                        }
                        else
                        {
                            CALoggingHelper.AddWarningEntry(string.Format("The {0} field cannot be found.", approver.InternalName, doclib.Title));
                        }
                    }

                    doclib.EnableFolderCreation = false; // Disable folder creation for this document library
                    CALoggingHelper.AddInformationEntry(string.Format("Folder creation disabled for {0} list.", doclib.Title));
                    doclib.ContentTypesEnabled = false; // Disable content types for this document library (hide the content type choice drop down)
                    CALoggingHelper.AddInformationEntry(string.Format("Content type disabled for {0} list.", doclib.Title));
                    doclib.Update();

                    SPList historyList = SPHelper.GetListByName(web, Constants.WorkflowHistoryList);
                    if (historyList == null)
                    {
                        historyList = SPHelper.CreateListeBasedOnTemplate(web, SPListTemplateType.WorkflowHistory, Constants.WorkflowHistoryList);
                    }

                    SPList taskList = SPHelper.GetListByName(web, Constants.WorkflowTasksList);
                    if (taskList == null)
                    {
                        taskList = SPHelper.CreateListeBasedOnTemplate(web, SPListTemplateType.Tasks, Constants.WorkflowTasksList);
                    }

                    SPHelper.AssociateWorkflowToList(web, doclib, historyList, taskList, Constants.WorkflowTemplateName, Constants.WorkflowAssociationName);
                }

                // Approved Knowledge List
                doclib = web.Lists[Constants.KnowledgeApprovedListTitle] as SPDocumentLibrary;
                if (doclib != null)
                {
                    // Hide title field (replaced by custom title, required)
                    SPHelper.HideField(doclib, "Title");
                    
                    doclib.EnableFolderCreation = false; // Disable folder creation for this document library
                    CALoggingHelper.AddInformationEntry(string.Format("Folder creation disabled for {0} list.", doclib.Title));
                    doclib.ContentTypesEnabled = false; // Disable content types for this document library (hide the content type choice drop down)
                    CALoggingHelper.AddInformationEntry(string.Format("Content type disabled for {0} list.", doclib.Title));
                    doclib.Update();
                }

                web.AllowUnsafeUpdates = allowUnsafeUpdates;
            }
        }


        // Uncomment the method below to handle the event raised before a feature is deactivated.

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            CALoggingHelper.AddInformationEntry(string.Format("Feature {0} ({1}) deactivated.", properties.Feature.Definition.DisplayName, properties.Feature.DefinitionId));
        }


        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
            CALoggingHelper.AddInformationEntry(string.Format("Feature {0} ({1}) uninstalled.", properties.Feature.Definition.DisplayName, properties.Feature.DefinitionId));
        }

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
    }
}
